/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package linkedlistdependentstack;
/**
*
* @author mweya
*/
import linkedlistdependentstack.Node;
public class LinkedList<AnyType> {
private Node head = null;
public LinkedList() {}
public LinkedList(AnyType data) {
this.head = new Node<>(data);
head.setNext(head);
head.setPrev(head);
}
public void add(AnyType data) {
if (head == null) {
head = new Node<>(data);
head.setNext(head);
head.setPrev(head);
}else {
Node currentNode = head;
while (currentNode.getNext() != head) {
currentNode = currentNode.getNext();
}
Node toInsert = new Node<>(data);
toInsert.setNext(head);
toInsert.setPrev(currentNode);
currentNode.setNext(toInsert);
head.setPrev(toInsert);
}
}
public void removeLast() {
Node newTail = head.getPrev().getPrev();
newTail.setNext(head);
}
public int getSize() {
Node currentNode = head;
int j = 0;
while(currentNode != head) {
j = j+1;
}
return j;
}
public Node getHead() {
return this.head;
}
public Node getTail() {
return this.head.getPrev();
}
@Override
public String toString() {
String out = "LinkedList=(";
Node currentNode = head;
do {
out = out+currentNode.getData()+", ";
currentNode = currentNode.getNext();
} while (currentNode.getNext() != head);
out = out+")";
return out;
}
}